package com.telecom.restaurant.interceptor;

import com.alibaba.fastjson.JSON;
import com.telecom.restaurant.constant.DataResultConstant;
import com.telecom.restaurant.constant.ManageThreadLocal;
import com.telecom.restaurant.util.EncryptUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by qiqi on 2019/12/2.
 */
public class ManageLoginInterceptor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(ManageLoginInterceptor.class);

    long expireTime = 3600l * 1000 * 24;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        String encryptData =  request.getHeader("restaurant_header");
        try{
            if(StringUtils.isNotBlank(encryptData)){
                String data = EncryptUtil.decrypt(encryptData);
                String[] dataArray = data.split("\\|");
                Long userId = Long.valueOf(dataArray[0]);
                Long restaurantId = Long.valueOf(dataArray[1]);
                Long timestamp = Long.valueOf(dataArray[2]);
                if(System.currentTimeMillis() - timestamp <= expireTime){
                    ManageThreadLocal.userId.set(userId);
                    ManageThreadLocal.restaurantId.set(restaurantId);
                    return true;
                }
            }
        }catch (Exception e){
            logger.warn("ManageLoginInterceptor error. encryptData:{}", encryptData, e);

        }

        returnJson(response, JSON.toJSONString(DataResultConstant.WRONG_TOKEN));
        return false;
    }
    private void returnJson(HttpServletResponse response, String json) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            logger.error("response error",e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }


    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}